package com.shelpe.services.sinbad.service.rpt;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.shelpe.services.sinbad.controller.dto.EffectDto;
import com.shelpe.services.sinbad.dao.RptCustomerMapper;
import com.shelpe.services.sinbad.entity.jpa.User;
import com.shelpe.services.sinbad.model.RptCustomer;
import com.shelpe.services.sinbad.repository.jpa.UserRepository;

@Service
public class UserService {
	@Autowired
	private RptCustomerMapper rptCustomerMapper;
	@Autowired
	private UserRepository userRepository;

	public EffectDto summariesMetric(long userID, String device, String startDate, String endDate) {
		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "该用户不存在");
		// PC站内:1， PC站外:2 , 移动站内:4，移动站外:5 ps: pc:12 mobile:45
		List<Integer> sources = new ArrayList<Integer>();
		if ("all".equals(device)) {
			sources.add(1);
			sources.add(2);
			sources.add(4);
			sources.add(5);
		} else if ("mobile".equals(device)) {
			sources.add(4);
			sources.add(5);
		} else if ("pc".equals(device)) {
			sources.add(1);
			sources.add(2);
		} else if ("instation".equals(device)) {
			sources.add(1);
			sources.add(4);
		} else if ("outstation".equals(device)) {
			sources.add(2);
			sources.add(5);
		} else if ("pcin".equals(device)) {
			sources.add(1);
		} else if ("pcout".equals(device)) {
			sources.add(2);
		} else if ("mobilein".equals(device)) {
			sources.add(4);
		} else if ("mobileout".equals(device)) {
			sources.add(5);
		}

		RptCustomer rpt = rptCustomerMapper.selectUserMetricSum(userID, startDate, endDate,
				"(" + StringUtils.join(sources, ",") + ")");

		EffectDto dto = new EffectDto();
		if (rpt != null) {
			dto.from(rpt);
		}

		return dto;
	}

	public List<EffectDto> userEffectTrend(long userID, String device, String startDate, String endDate) {
		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "该用户不存在");
		int lower = 1;
		int upper = 5;
		if (device.equals("mobile")) {
			lower = 4;
			upper = 5;
		} else if (device.equals("pc")) {
			lower = 1;
			upper = 2;
		}
		List<RptCustomer> rpts = rptCustomerMapper.selectUserTrendSum(userID, startDate, endDate, lower, upper);
		List<EffectDto> dtos = new ArrayList<EffectDto>();
		if (rpts != null) {
			for (RptCustomer rpt : rpts) {
				EffectDto dto = new EffectDto();
				dto.from(rpt);
				dtos.add(dto);
			}
		}
		return dtos;
	}
}
